package com.turkcell.dv.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.turkcell.dv.model.UserPrivilegeDOM;

import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional(readOnly = true)
public class UserPrivilegeDAOImpl implements UserPrivilegeDAO{

	private static final Logger logger = LoggerFactory.getLogger(UserPrivilegeDAOImpl.class);
	 
	@Autowired private SessionFactory sessionFactory;
    
    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

	@Override
	public void addUserPrivilege(UserPrivilegeDOM up) {
		Session session = this.sessionFactory.getCurrentSession();
        session.persist(up);
        logger.info("User saved successfully, User Details= " + up);
		
	}

	@Override
	public void removeUserPrivilege(long id) {
        Session session = this.sessionFactory.getCurrentSession();
        UserPrivilegeDOM up = (UserPrivilegeDOM) session.load(UserPrivilegeDOM.class, new Long(id));
        if(null != up){
            session.delete(up);
        }
        logger.info("UserPrivilege deleted successfully, UserPrivilege details=" + up);		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserPrivilegeDOM> listUserPrivilegesByUserId(long userId) {
        Session session = this.sessionFactory.getCurrentSession();
		Query query = session.createQuery("from UserPrivilegeDOM UP WHERE UP.userId = :userId");
		query.setParameter("userId", userId);
		List<UserPrivilegeDOM> userPrivilegesList = query.list();
        for(UserPrivilegeDOM u : userPrivilegesList){
            System.out.println("User List::" + u);
        }
        return userPrivilegesList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserPrivilegeDOM> listUserPrivilegesByPrivilegeId(long privilegeId) {
        Session session = this.sessionFactory.getCurrentSession();
		Query query = session.createQuery("from UserPrivilegeDOM UP WHERE UP.privilegeId = :privilegeId");
		query.setParameter("privilegeId", privilegeId);
		List<UserPrivilegeDOM> userPrivilegesList = query.list();
        for(UserPrivilegeDOM u : userPrivilegesList){
            logger.info("User List::" + u);
        }
        return userPrivilegesList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public UserPrivilegeDOM getUserPrivilegeById(long id) {
        Session session = this.sessionFactory.getCurrentSession();
		Query query = session.createQuery("from UserPrivilegeDOM UP WHERE UP.id = :id");
		query.setParameter("id", id);
		List<UserPrivilegeDOM> userPrivilegesList = query.list();
        return userPrivilegesList.get(0);
	}

}
